import React, {
    PureComponent
} from 'react';

import {
    StyleSheet
} from 'react-native';

import {
    Actions
} from 'react-native-router-flux';

import PropsTypes from 'prop-types';

import SwipeOut from 'react-native-swipeout';

import {
    Tip,

    Layout,
    Empty,
    Loading,
    ListView
} from './../../../components';

import MsgRow from './row';

import * as CONST from "../../../const";
import LikeAir from './../components/likeAir';

import connect from './../../../utils/connect';
import chatAction from './../../../state/actions/chat';
import * as chatTypes from './../../../state/types/chat';

interface Props {
    chat: any,
    user: any,
    chatActions: any
}

interface State {
    enableScroll:boolean
}

@connect([`chat`, `user`], {
    chatActions: chatAction
})
class Chat extends PureComponent <Props,State> {
    static curChatUserId:number = 0;
    static curChatRoomId:string = '';

    isFirstIn:boolean = true;

    state = {
        enableScroll:true
    }

    static contextTypes = {
        listenTabIn:PropsTypes.func
    }

    get queryList() {
        const {
            chat
        } = this.props;

        const {
            lists = {}
        } = chat;
        return lists[this.loginUserId] || [];
    }

    componentDidMount() {
        this.context.listenTabIn(
            this.onTabPageShow
        )
    }

    public onTabPageShow = () => {
        if(!this.isFirstIn) {
            this.onRefresh(() => null)
        }
    }

    get unread() {
        const {
            chat
        } = this.props;
        const {
            unRead={}
        } = chat;
        return unRead;
    }

    get lastId() {
        const {
            length
        } = this.queryList;
        const {
            chatId = 0
        } = this.queryList[length - 1] || {};
        return chatId;
    }

    get loginUserId() {
        const {
            user
        } = this.props;

        const {
            loginUser
        } = user || {};

        const {
            userId = 0
        } = loginUser || {};

        return userId;
    }

    get chatActions() {
        const {
            chatActions
        } = this.props;
        return chatActions;
    }
    
    get empty() {
        return (
            <Empty
               title="-- No any data -- "
            />
        )
    }

    private rightButton(item:any) {
        return [{
            text: 'Delete',
            backgroundColor: CONST.color,
            onPress: () => this._onDelete(item)
        }]
    }

    private _onDelete = async ({userId}:any) => {
        Loading.show();
        try {
            await this.chatActions[
                chatTypes.deleteMessageRow
            ](userId)
        }
        catch (e) {
            Tip.warm({
                message:e.message
            })
        }
        Loading.close()
    }

    private onScrollView = (scroll:boolean) => {
        this.setState({
            enableScroll:scroll
        })
    }

    private _renderItem = ({item}:any) => {
        const {
            chatRoomId
        } = item;
        const dotNum = (
            this.unread[chatRoomId] || 0
        )
        return (
            <SwipeOut
                autoClose={true}
                style={styles.itemStyle}
                scroll={this.onScrollView}
                backgroundColor="transparent"
                right={this.rightButton(item)}
            >
                <MsgRow
                    data={item}
                    dotNum={dotNum}
                    onPress={this.toChatPress}
                />
            </SwipeOut>
        )
    }

    private toChatPress = (item:any) => {
        Actions.push(`/message`,{
            userId:~~item.userId,
            nickName:item.userName
        })
    }

    private onRefresh = (done: Function) => {
        this.onFetchList(0, done);
    }

    private onLoadPage = (done: Function) => {
        this.onFetchList(this.lastId, done);
    }

    private onFetchList = async (
        lastId: any = 0,
        done: Function
    ) => {
        let list = [];
        let success = true;
        try {
            const _para = {
                lastId: lastId,
                isPush: !!lastId
            }
            list = await this.chatActions[
                chatTypes.getUserMessageList
            ](_para)
        }
        catch (e) {
            success = false;
            Tip.warm({
                message: e.message
            })
        }
        done(list, success);
        this.isFirstIn = false;
    }

    render() {
        const {
            enableScroll
        } = this.state;
        return (
            <Layout
                scroll={false}
                backShow={false}
                padding={false}
                title="Message"
            >
                <ListView
                    limit={300}
                    data={this.queryList}
                    onLoadTop={this.onRefresh}
                    scrollEnabled={enableScroll}
                    renderItem={this._renderItem}
                    onLoadPage={this.onLoadPage}
                    ListEmptyComponent={this.empty}
                />
            </Layout>
        )
    }
}

export default Chat;

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    header: {
        height: 44,
        justifyContent: `center`,
        paddingHorizontal: 16
    },
    emptyIcon:{
        width:210,
        height:210
    }
}) as any;